<template>
  <div v-loading="dataLoading || optionsLoading" class="app-container">
    <div class="data-content">
      <div class="action-content">
        <el-row :gutter="10">
          <el-col :span="14">
            <span style="font-size: x-large; margin-right: 10px">{{ $t('inboundScan') }}</span>
            <span style="color: grey">{{ $t('inbound.orderNo') }} {{ orderInfo.orderNo }}</span>
            <br><br>
            <span style="color: red">{{ $t('inbound.warning') }}</span>
          </el-col>
          <el-col :span="9">
            <el-button :disabled="currentTab === '1' || selectedList.length === 0" type="primary" style="float: right"
              @click="confirmInound">{{ $t('inbound.confirm') }}</el-button>
          </el-col>
        </el-row>
        <el-row :gutter="10" style="margin-top: 10px">
          <el-col :span="12">
            <el-input ref="boxNoInput" v-model="boxNo" :placeholder="$t('inbound.pleaseScanBoxNo')" clearable
              @keyup.enter.native.prevent="handleScanBox">
              <i slot="prefix" class="el-icon-full-screen scan-icon" />
            </el-input>
          </el-col>
          <el-col :span="12">
            <el-input ref="skuCodeInput" v-model="skuCode" :placeholder="$t('inbound.pleaseScanSku')" clearable
              @keyup.enter.native.prevent="handleScanSku">
              <i slot="prefix" class="el-icon-full-screen scan-icon" />
            </el-input>
          </el-col>
        </el-row>
      </div>
      <el-tabs v-model="currentTab" @tab-click="handleTabSwitch">
        <el-tab-pane :label="$t('inbound.statusNew')" name="0" />
        <el-tab-pane :label="$t('inbound.statusFinished')" name="1" />
      </el-tabs>
      <div class="table-content">
        <el-table ref="orderTable" :data="tableData" height="100%" style="width: 100%" stripe highlight-current-row
          @selection-change="handleSelectionChange" @current-change="handleCurrentChange">
          <el-table-column v-if="currentTab === '0'" type="selection" width="55" align="center" />
          <el-table-column type="expand" width="45" align="center">
            <template slot-scope="scope">
              <el-table :data="scope.row.orderInfoBoxSkuDTOList" :show-header="false">
                <el-table-column :width="currentTab === '0' ? 100 : 45" align="center" />
                <el-table-column min-width="150" prop="skuCode" align="center" />
                <el-table-column min-width="100" prop="receiveStatus" align="center">
                  <template v-slot="{ row }">
                    {{ row.receiveStatus === 0 ? $t("warehousingLang.firstArrival") :
                      $t("warehousingLang.toTheWarehouseAgain") }}
                  </template>
                </el-table-column>
                <el-table-column min-width="150" prop="packagingType" align="center">
                  <template v-slot="{ row }">
                    <span v-if="currentTab === '1'">{{$t('warehousingLang.' + packagingTypeEnum.find(item => item.value
                      === row.packagingType).title)}}</span>
                    <el-select v-else v-model="row.packagingType">
                      <el-option v-for="item in packagingTypeEnum" :key="item.value" :value="item.value"
                        :label="$t('warehousingLang.' + item.title)" />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column min-width="250" prop="realSize" align="center">
                  <template v-slot="{ row }">
                    <span v-if="currentTab === '1'">{{ row.skuLength }}*{{ row.skuWidth }}*{{ row.skuHeight }} CM</span>
                    <el-row v-else :gutter="5">
                      <el-col :span="7"><el-input v-model="row.realLength" /></el-col>
                      <el-col :span="7"><el-input v-model="row.realWidth" /></el-col>
                      <el-col :span="10">
                        <el-input v-model="row.realHeight">
                          <span slot="suffix" class="el-input__icon">CM</span>
                        </el-input>
                      </el-col>
                        <div style="font-size: 12px;text-align: left;">{{$t('goodsSKULang.declare')}}{{$t('goodsSKULang.volume')}}：{{ row.skuLength||0 }}*{{ row.skuWidth||0 }}*{{ row.skuHeight||0 }} CM</div>

                    </el-row>
                  </template>
                </el-table-column>
                <el-table-column prop="realWeight" min-width="100" align="center">
                  <template v-slot="{ row }">
                    <span v-if="currentTab === '1'">{{ row.skuWeight }} KG</span>
                    <template v-else>
                      <el-input v-model="row.realWeight">
                        <span slot="suffix" class="el-input__icon">KG</span>
                      </el-input>
                      <div style="font-size: 12px;text-align: left;">{{$t('goodsSKULang.declare')}}{{$t('goodsSKULang.weight')}}：{{row.skuWeight||0  }}KG</div>
                    </template>
                   
                  </template>
                </el-table-column>
                <el-table-column prop="preSkuNum" min-width="100" align="center" />
                <el-table-column prop="receiptNum" min-width="100" align="center">
                  <template v-slot="{ row }">
                    <span v-if="currentTab === '1'">{{ row.receiptNum }}</span>
                    <el-input v-else v-model="row.receiptNum" />
                  </template>
                </el-table-column>
                <el-table-column prop="originalBox" min-width="100" align="center" />
                <el-table-column prop="locationCode" min-width="250" align="center">
                  <template v-slot="{ row }">
                    <div v-if="currentTab === '1' && !scope.row.originalBox">
                      <el-row v-for="(location, i) in row.locations" :key="i" :gutter="5" style="margin-bottom: 2px">
                        <span>{{ location.locationCode }} * {{ location.shelveNum }}</span>
                      </el-row>
                    </div>
                    <div v-else-if="!scope.row.originalBox">
                      <el-row v-for="(location, i) in row.locations" :key="i" :gutter="5" style="margin-bottom: 2px">
                        <el-col :span="14">
                          <el-select v-model="location.locationCode" filterable remote
                            :remote-method="filterSkuLocation" clearable
                            @focus="skuLocationFocus(row.referLocationCode)">
                            <el-option-group v-for="group in skuLocationOptions" :key="group.label"
                              :label="group.label">
                              <el-option v-for="item in group.options" :key="item.value" :value="item.value"
                                :label="item.value">
                                <span style="float: left">{{ item.value }}</span>
                                <span style="float: right; color: #8492a6; font-size: 13px">{{ $t('locationLang.' +
                                  item.label) }}</span>
                              </el-option>
                            </el-option-group>
                          </el-select>
                        </el-col>
                        <el-col :span="10" style="display: flex">
                          <el-input v-model="location.shelveNum" style="flex: 1; margin-right: 4px" />
                          <el-button v-if="row.locations.length > 1" type="text" icon="el-icon-remove-outline"
                            @click="row.locations.splice(i, 1)" />
                        </el-col>
                      </el-row>
                      <el-row :gutter="5">
                        <el-col :span="14">
                          <el-button type="text" icon="el-icon-plus" @click="row.locations.push({})">{{
                            $t('inbound.addLocation') }}</el-button>
                        </el-col>
                      </el-row>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column :label="$t('inbound.boxNo')" min-width="150" prop="boxNo" align="center" />
          <el-table-column :label="$t('inbound.receiveStatus')" min-width="100" prop="receiveStatus" align="center" />
          <el-table-column min-width="150" prop="packagingType" align="center">
            <template slot="header">
              <span v-if="currentTab === '0'" style="color: red">*</span>{{ $t('inbound.packagingType') }}
            </template>
          </el-table-column>
          <el-table-column min-width="250" prop="realSize" align="center">
            <template slot="header">
              <span v-if="currentTab === '0'" style="color: red">*</span>{{ $t('inbound.realSize') }}
            </template>
            <template slot-scope="scope">
              <span v-if="currentTab === '1'">{{ scope.row.boxLength }}*{{ scope.row.boxWidth }}*{{ scope.row.boxHeight
                }} CM</span>
              <el-row v-else :gutter="5">
                <el-col :span="7"><el-input v-model="scope.row.boxLength" /></el-col>
                <el-col :span="7"><el-input v-model="scope.row.boxWidth" /></el-col>
                <el-col :span="10">
                  <el-input v-model="scope.row.boxHeight">
                    <span slot="suffix" class="el-input__icon">CM</span>
                  </el-input>
                </el-col>
                <div style="font-size: 12px;text-align: left;">{{$t('goodsSKULang.declare')}}{{$t('goodsSKULang.volume')}}：{{ scope.row.initBox.boxLength||0 }}*{{ scope.row.initBox.boxWidth||0 }}*{{ scope.row.initBox.boxHeight||0
                  }} CM</div>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column prop="realWeight" min-width="120" align="center">
            <template slot="header">
              <span v-if="currentTab === '0'" style="color: red">*</span>{{ $t('inbound.realWeight') }}
            </template>
            <template slot-scope="scope">
              <span v-if="currentTab === '1'">{{ scope.row.boxWeight }} KG</span>
              <template v-else>
                <el-input v-model="scope.row.boxWeight">
                  <span slot="suffix" class="el-input__icon">KG</span>
                </el-input>
                <div style="font-size: 12px;text-align: left;">{{$t('goodsSKULang.declare')}}{{$t('goodsSKULang.weight')}}: {{ scope.row.initBox.boxWeight||0 }} KG</div>
              </template>
            </template>
          </el-table-column>
          <el-table-column :label="$t('inbound.forecastNum')" prop="boxPreNum" min-width="100" align="center" />
          <el-table-column prop="receiptNum" min-width="100" align="center">
            <template slot="header">
              <span v-if="currentTab === '0'" style="color: red">*</span>{{ $t('inbound.receiptNum') }}
            </template>
          </el-table-column>
          <el-table-column prop="originalBox" min-width="100" align="center">
            <template slot="header">
              <span>{{ $t('inbound.isOriginalBoxShelve') }}</span>
              <el-tooltip v-if="currentTab === '0'" style="margin-left: 3px" placement="top"
                :content="$t('inbound.originalBoxTooltip')">
                <i class="el-icon-info" />
              </el-tooltip>
            </template>
            <template slot-scope="scope">
              <el-checkbox v-model="scope.row.originalBox" :disabled="currentTab === '1'">{{ $t('inbound.originalBox')
                }}</el-checkbox>
            </template>
          </el-table-column>
          <el-table-column prop="locationCode" min-width="250" align="center">
            <template slot="header">
              <div v-if="currentTab === '0'">
                <span style="color: red">*</span>{{ $t('inbound.referLocationAndNum') }}
              </div>
              <span v-else>{{ $t('inbound.locationAndNum') }}</span>
            </template>
            <template slot-scope="scope">
              <span v-if="currentTab === '1'">{{ scope.row.locationCode }}</span>
              <!--              <el-select v-else-if="scope.row.originalBox" v-model="scope.row.locationCode" filterable :filter-method="filterBoxLocation" allow-create clearable @focus="boxLocationFocus">-->
              <!--                <el-option v-for="item in boxLocationOptions" :key="item.value" :value="item.value" :label="item.value">-->
              <!--                  <span style="float: left">{{ item.value }}</span>-->
              <!--                  <span style="float: right; color: #8492a6; font-size: 13px">{{ $t('locationLang.' + item.label) }}</span>-->
              <!--                </el-option>-->
              <!--              </el-select>-->
              <el-input v-else v-model="scope.row.locationCode" />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import { confirmFastInound, getOrderInfo } from '@/api/business/warehouseManage/inbound';
import { scanFail, scanSuccess } from '@/utils/validate';
import { locationPickTypeDict, packageTypeDict } from '@/utils/dictData';
import { getDictOptionList, getTitleByValue } from '@/utils/dictUtils';
import { getDepotLocationForFree } from '@/api/business/depotManage/location';

export default {
  name: 'FastInbound',
  components: {},
  data () {
    return {
      dataLoading: false,
      optionsLoading: false,
      currentTab: '0',
      orderInfo: {},
      boxNo: null,
      skuCode: null,
      packagingTypeEnum: getDictOptionList(packageTypeDict),
      currentBox: null,
      tableData: [],
      selectedList: [],
      locationList: [],
      boxLocationOptions: [],
      skuLocationOptions: [],
    }
  },
  created () {
    this.getDepotLocationForFree()
    this.getOrderInfo(this.$route.params.orderNo)
  },
  methods: {
    handleTabSwitch () {
      this.dataLoading = true
      this.tableData = this.orderInfo.orderInfoBoxDTOList.filter(item => {
        if (this.currentTab === '0') {
          return item.boxStatus === 0
        } else {
          return item.boxStatus !== 0
        }
      })
      if (this.currentTab === '0') {
        const selectedListTemp = this.selectedList;
        const currentBoxTemp = this.currentBox;
        this.$nextTick(() => {
          selectedListTemp.forEach(row => this.$refs.orderTable.toggleRowSelection(row, true))
          this.$refs.orderTable.setCurrentRow(currentBoxTemp);
          this.$refs.orderTable.toggleRowExpansion(currentBoxTemp, true);
          this.dataLoading = false
        })
      } else {
        this.dataLoading = false
      }
    },
    scrollToCurrentRow () {
      this.$nextTick(() => {
        this.$refs.orderTable.toggleRowExpansion(this.currentBox, true);
        const currentRow = this.$refs.orderTable.$el.getElementsByClassName('current-row')[0]
        if (currentRow) {
          this.$refs.orderTable.bodyWrapper.scrollTo({ top: currentRow.offsetTop, behavior: 'smooth' })
        }
      })
    },
    handleCurrentChange (currentRow, oldCurrentRow) {
      if (this.currentTab === '0') {
        this.currentBox = currentRow
      }
      this.$refs.orderTable.toggleRowExpansion(currentRow, true);
    },
    handleScanBox () {
      this.currentBox = this.orderInfo.orderInfoBoxDTOList.find(item => item.boxStatus === 0 && item.boxNo === this.boxNo)
      if (this.currentBox) {
        scanSuccess()
        this.currentTab = '0'
        this.selectedList.push(this.currentBox)
        this.handleTabSwitch();
        this.$nextTick(() => {
          this.$refs.skuCodeInput.focus()
          this.scrollToCurrentRow()
        })
      } else {
        this.boxNo = null
        scanFail()
      }
    },
    handleScanSku () {
      if (this.currentTab === '0') {
        const currentSku = this.currentBox?.orderInfoBoxSkuDTOList.find(item => item.skuCode === this.skuCode)
        if (currentSku) {
          scanSuccess()
          currentSku.receiptNum += 1
        } else {
          scanFail()
        }
      }
      this.skuCode = null
    },
    handleSelectionChange (rows) {
      if (this.currentTab === '0') {
        this.selectedList = rows;
      }
    },
    async getOrderInfo (orderNo) {
      this.dataLoading = true;
      await getOrderInfo({ orderNo: orderNo }).then((res) => {
        this.$refs.boxNoInput.focus()
        res.data.orderInfoBoxDTOList.forEach(box => {
          box.originalBox = box.originalBox !== 0
          box.locationCode = ''
          box.initBox = {
            boxHeight: box.boxHeight,
            boxLength: box.boxLength,
            boxWidth: box.boxWidth,
            boxWeight: box.boxWeight,
          }
          if (box.originalBox && box.orderInfoBoxSkuDTOList?.length > 0 && box.orderInfoBoxSkuDTOList[0].stockBatchList?.length > 0) {
            box.locationCode = box.orderInfoBoxSkuDTOList[0].stockBatchList[0].locationCode
          }
          box.orderInfoBoxSkuDTOList.forEach(sku => {
            if (box.boxStatus !== 0) {
              sku.locations = sku.stockBatchList?.map(stock => {
                return { locationCode: stock.locationCode, shelveNum: stock.skuNum }
              })
            } else {
              sku.locations = [{}]
            }
            if (sku.receiveStatus !== 0) {
              sku.realLength = sku.skuLength
              sku.realWidth = sku.skuWidth
              sku.realHeight = sku.skuHeight
              sku.realWeight = sku.skuWeight
            }
          })
        })
        this.orderInfo = res.data;
        this.handleTabSwitch()
      }).finally(() => {
        this.dataLoading = false;
      })
    },
    async getDepotLocationForFree () {
      this.optionsLoading = true
      await getDepotLocationForFree({ freeFlag: 1, locationstatus: 1 }).then((res) => {
        this.locationList = res.data.resultList.map(item => {
          return { value: item.locationCode, label: getTitleByValue(getDictOptionList(locationPickTypeDict), item.pickType) }
        })
      }).finally(() => {
        this.optionsLoading = false;
      })
    },
    skuLocationFocus (referLocations) {
      const options0 = referLocations.map(item => {
        return {
          value: item.locationCode,
          label: getTitleByValue(getDictOptionList(locationPickTypeDict), item.pickType)
        }
      })
      const options1 = this.locationList.slice(0, 10)
      this.setSkuLocation(options0, options1)
    },
    filterSkuLocation (value) {
      const options0 = this.skuLocationOptions[0].options.filter(item => !value || item.value.toLowerCase().includes(value.toLowerCase()))
      const options1 = this.locationList.filter(item => !value || item.value.toLowerCase().includes(value.toLowerCase()))
      this.setSkuLocation(options0, options1)
    },
    setSkuLocation (options0, options1) {
      this.skuLocationOptions = [{
        label: this.$t('inbound.referLocation'),
        options: options0
      }, {
        label: this.$t('inbound.freeLocation'),
        options: options1
      }]
    },
    boxLocationFocus () {
      this.boxLocationOptions = this.locationList.slice(0, 10);
    },
    filterBoxLocation (value) {
      this.boxLocationOptions = this.locationList.filter(item => !value || item.value.toLowerCase().includes(value.toLowerCase())).slice(0, 10);
    },
    validateBox (box) {
      return (!box.originalBox) || (box.boxLength > 0 && box.boxWidth > 0 && box.boxHeight > 0 && box.boxWeight > 0 && (!box.originalBox || box.locationCode))
    },
    validateSku (box, sku) {
      return box.originalBox || (sku.packagingType != null && sku.realLength > 0 && sku.realWidth > 0 && sku.realHeight > 0 && sku.realWeight > 0 && sku.receiptNum >= 0 && !sku.locations.find(item => !(item.shelveNum > 0 && item.locationCode)))
    },
    confirmInound () {
      if (this.selectedList.length <= 0) return
      const request = {
        fromTerminal: 0,
        orderId: this.orderInfo.orderId,
        orderInfoForReceiptList: []
      }
      const infoArr = []
      for (const box of this.selectedList) {
        if (!this.validateBox(box)) {
          this.$message.error(this.$t('pleaseCheck') + this.$t('required'))
          this.$refs.orderTable.setCurrentRow(box);
          this.scrollToCurrentRow()
          return
        }
        for (const sku of box.orderInfoBoxSkuDTOList) {
          if (!this.validateSku(box, sku)) {
            this.$message.error(this.$t('pleaseCheck') + this.$t('required'))
            this.$refs.orderTable.setCurrentRow(box);
            this.scrollToCurrentRow()
            return
          }

          if (box.originalBox) {
            request.orderInfoForReceiptList.push({
              boxId: box.boxId,
              boxLength: box.boxLength,
              boxWidth: box.boxWidth,
              boxHeight: box.boxHeight,
              boxWeight: box.boxWeight,
              skuId: sku.skuId,
              packagingType: sku.packagingType,
              skuLength: sku.realLength,
              skuWidth: sku.realWidth,
              skuHeight: sku.realHeight,
              skuWeight: sku.realWeight,
              receiptNum: sku.receiptNum,
              preNum: sku.preSkuNum,
              originalBox: 1,
              locationCode: box.locationCode,
            })
          } else {
            request.orderInfoForReceiptList = request.orderInfoForReceiptList.concat(sku.locations.map(location => {
              return {
                boxId: box.boxId,
                boxLength: box.boxLength,
                boxWidth: box.boxWidth,
                boxHeight: box.boxHeight,
                boxWeight: box.boxWeight,
                skuId: sku.skuId,
                packagingType: sku.packagingType,
                skuLength: sku.realLength,
                skuWidth: sku.realWidth,
                skuHeight: sku.realHeight,
                skuWeight: sku.realWeight,
                receiptNum: location.shelveNum,
                originalBox: 0,
                locationCode: location.locationCode,
              }
            }))
            const temp = sku.locations.reduce((total, location) => {
              return total + (location.shelveNum ?? 0)
            }, 0)
            const isRu = this.$store.getters.language === 'ru_RU'
            if (temp > sku.preSkuNum) {
              infoArr.push(`${isRu ? '【' : ''}${this.$t('inbound.receiptNum')} > ${this.$t('inbound.forecastNum1')}${isRu ? '】' : ''}`)
            } else if (temp < sku.preSkuNum) {
              infoArr.push(`${isRu ? '【' : ''}${this.$t('inbound.receiptNum')} < ${this.$t('inbound.forecastNum1')}${isRu ? '】' : ''}`)
            }
          }
        }
      }
      if (infoArr.length > 0) {
        this.$confirm(infoArr[0], {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning',
        }).then(() => {
          this.confirmModal(request);
        })
      } else {
        this.confirmModal(request);
      }
    },
    confirmModal (request) {
      this.dataLoading = true;
      confirmFastInound(request).then((res) => {
        if (!res || res.returnCode !== 10000) return
        this.$confirm(this.$t('inbound.inboundSuccess'), '', {
          confirmButtonText: this.$t('inbound.continuScan'),
          cancelButtonText: this.$t('cancel'),
          type: 'success',
          center: true
        }).then(() => {
          this.$router.push({ name: 'InboundScan' })
          this.confirmInoundSuccess()
        }).catch(() => {
          this.confirmInoundSuccess()
        });
      }).finally(() => {
        this.dataLoading = false;
      })
    },
    confirmInoundSuccess () {
      this.boxNo = null
      this.skuCode = null
      this.currentTab = '1'
      this.currentBox = null
      this.selectedList = []
      this.getOrderInfo(this.orderInfo.orderNo)
      this.getDepotLocationForFree()
      this.$nextTick(() => {
        this.$refs.orderTable.clearSelection();
      })
    },
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  position: absolute;
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: auto;
}

.data-content {
  padding: 20px;
  flex: 1;
  border: 1px solid #e6ebf5;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
  display: flex;
  flex-direction: column;
  min-height: 500px;
  overflow: hidden;

  .action-content {
    margin-bottom: 5px;

    ::v-deep .el-input__inner {
      height: 50px;
      padding-left: 45px;
    }

    .scan-icon {
      margin: 15px 15px 0 10px;
      font-size: 20px
    }
  }

  .table-content {
    flex: 1;
    overflow: hidden;
  }
}
</style>
